#include <math.h>
#include "xlx_platform.h"
#include "xlx_utils.h"

static const char* TAG = "Utils";

int xlx_imei_check(const char *imei, char *out) {
    if (!imei) return -1;
    int len = strlen(imei);
    memcpy(out, imei, len);
    if (len >= 15) {
        return 0;
    }

    for (int i = len; i < 14; i++) {
        out[i] = '0';
    }

    int vl_Sum1 = 0, vl_Sum2 = 0, vl_Total = 0, vl_Temp = 0;
    for (int i = 0; i < 14; i++) {
        if ((i % 2) == 0) {
            vl_Sum1 = vl_Sum1 + imei[i] - 0x30;
        } else {
            vl_Temp = (imei[i] - 0x30) * 2;
            if (vl_Temp < 10) {
                vl_Sum2 = vl_Sum2 + vl_Temp;
            } else {
                vl_Sum2 = vl_Sum2 + 1 + vl_Temp - 10;
            }
        }
    }
    vl_Total = vl_Sum1 + vl_Sum2;
    int lastnumber = 0;
    if ((vl_Total % 10) != 0) {
		lastnumber = 10 - (vl_Total % 10);
	}
    out[14] = 0x30 + lastnumber;

    return 0;
}
